#! /usr/bin/python3
# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
# import json
import pyperclip
from hashlib import md5
import time
from threading import Thread

# 造一个线程用于退出，使用全局变量A通信。
A = 'a'


def foo():
    global A   # 全局变量要在子函数中声明
    a = ''
    while a != 'q':
        a = input()
    A = a
    return A


thd = Thread(target=foo)
thd.daemon = True
thd.start()

# Set your own appid/appkey.
appid = '20211105000991769'
appkey = 'BGMumlXi6QJWE0mmcjCd'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang = 'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path


def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


# query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
# 处理剪切板中的内容函数：
def inputs():
    query = pyperclip.paste()
    query = query.replace("\n", " ")
    query = query.replace("\r", " ")
    query = query.replace("\t", " ")
    for i in range(8, 2, -1):
        query = query.replace(" "*i, " ")
    query = query.replace("‐ ", "")
    # print(query)
    return query


q0 = '_'
while 1:
    q1 = inputs()
    salt = random.randint(32768, 65536)
    sign = make_md5(appid + q1 + str(salt) + appkey)
    if len(q0) != len(q1):
        # Generate salt and sign
        # Build request
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'appid': appid, 'q': q1, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
        
        # Send request
        r = requests.post(url, params=payload, headers=headers)
        result = r.json()
        
        # Show response
        # 打印待翻译内容
        print(q1)
        # 打印翻译结果
        print(result['trans_result'][0]['dst'])
        print('-------------- 等待中,退出(q) ------------')
        # 记录待翻译内容，用于下次循环比较
        q0 = q1
    else:
        pass
    if A == 'q':
        break
    time.sleep(1)
